/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.finance.ar.memo.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.hibernate.exception.ConstraintViolationException;
import org.redragon.framework.hibernate.data.RDDataBox;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.redragon.framework.util.JsonDataUtil;
import org.redragon.framework.util.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.common.ar.receipt.service.ArReceiptHeadService;
import com.erp.common.voucher.service.FinVoucherBillRService;
import com.erp.common.voucher.service.FinVoucherHeadService;
import com.erp.common.voucher.service.FinVoucherModelHeadService;
import com.erp.cux.workflow.controller.CuxControllerSupport;
import com.erp.dataset.service.DatasetCommonService;
import com.erp.finance.ar.invoice.dao.model.ArInvoiceHead;
import com.erp.finance.ar.invoice.service.ArInvoiceHeadService;
import com.erp.finance.ar.memo.dao.data.DataBox;
import com.erp.finance.ar.memo.dao.model.ArInvoiceMemoHead;
import com.erp.finance.ar.memo.dao.model.ArInvoiceMemoHeadBase;
import com.erp.finance.ar.memo.dao.model.ArInvoiceMemoHeadCO;
import com.erp.finance.ar.memo.dao.model.ArInvoiceMemoLine;
import com.erp.finance.ar.memo.service.ArInvoiceMemoHeadService;
import com.erp.finance.ar.memo.service.ArInvoiceMemoLineService;
import com.erp.finance.ar.receipt.service.ArReceiptLineService;
import com.erp.finance.areco.memo.service.ArInvoiceMemoEcoService;
import com.erp.finance.areco.memo.service.ArInvoiceMemoHeadMService;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.masterdata.customer.dao.model.MdCustomer;
import com.erp.masterdata.vendor.dao.model.MdVendorBank;
import com.erp.masterdata.vendor.dao.model.MdVendorBankCO;
import com.erp.masterdata.vendor.service.MdVendorBankService;
import com.erp.order.so.dao.model.SoHead;
import com.erp.order.so.dao.model.SoHeadCO;
import com.erp.order.so.service.SoHeadService;
import com.erp.order.so.service.SoLineService;

@Controller
@RequestMapping("/web/arInvoiceMemoHead")
public class ArInvoiceMemoHeadWebController extends CuxControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(ArInvoiceMemoHeadWebController.class);
    
    //服务层注入
    @Autowired
    private ArInvoiceMemoHeadService arInvoiceMemoHeadService;
    @Autowired
    private ArInvoiceMemoLineService arInvoiceMemoLineService;
    @Autowired
    private ArInvoiceHeadService arInvoiceHeadService;
//    @Autowired
//    private ArInvoiceLineService arInvoiceLineService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private HrCommonService hrCommonService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private MdVendorBankService mdVendorBankService;
    @Autowired
    private SoHeadService soHeadService;
    @Autowired
    private SoLineService soLineService;
    @Autowired
    @Qualifier("finVoucherModelHeadServiceCommon")
    private FinVoucherModelHeadService finVoucherModelHeadService;
    @Autowired
    @Qualifier("finVoucherHeadServiceCommon")
    private FinVoucherHeadService finVoucherHeadService;
    @Autowired
    @Qualifier("finVoucherBillRServiceCommon")
    private FinVoucherBillRService finVoucherBillRService;
    @Autowired
    @Qualifier("arReceiptHeadServiceCommon")
    private ArReceiptHeadService arReceiptHeadService;
    @Autowired
    private ArReceiptLineService arReceiptLineService;
    @Autowired
    private ArInvoiceMemoEcoService invoiceMemoEcoService;
    @Autowired
    private ArInvoiceMemoHeadMService arInvoiceMemoHeadMService;
    
    
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getArInvoiceMemoHeadList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-10-27 14:36:38
     * @author 
     * @param pages
     * @param arInvoiceMemoHeadCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getArInvoiceMemoHeadList")
    public String getArInvoiceMemoHeadList(Pages pages, ArInvoiceMemoHeadCO arInvoiceMemoHeadCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        
        //分页查询数据
        List<ArInvoiceMemoHead> arInvoiceMemoHeadList = this.arInvoiceMemoHeadService.getDataObjectsForDataAuth("", pages, arInvoiceMemoHeadCO);
        
        //收款来源类型
        Map receiptSourceTypeMap = DataBox.getArInvoiceMemoSourceType();
        //状态
        Map receiptStatusMap = RDDataBox.getStatusMap();
        //获取出纳状态
        Map receivedStatusMap = DataBox.getReceivedStatusMap();
        //获取客户
        Map customerMap = this.masterDataCommonService.getCustomerMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //发票类型
        Map invoiceTypeMap = DataBox.getArInvoiceMemoType();
        
        //循环设置职员和组织信息
        for(ArInvoiceMemoHead arInvoiceMemoHead: arInvoiceMemoHeadList) {
            arInvoiceMemoHead.setStaffName(this.hrCommonService.getHrStaff(arInvoiceMemoHead.getStaffCode()).getStaffName());
            arInvoiceMemoHead.setDepartmentName(this.hrCommonService.getHrDepartment(arInvoiceMemoHead.getDepartmentCode()).getDepartmentName());
        }
        
        //页面属性设置
        model.addAttribute("receiptHeadList", arInvoiceMemoHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("receiptSourceTypeMap", receiptSourceTypeMap);
        model.addAttribute("receiptStatusMap", receiptStatusMap);
        model.addAttribute("receivedStatusMap", receivedStatusMap);
        model.addAttribute("customerMap", customerMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("invoiceTypeMap", invoiceTypeMap);
        //工作流属性
        this.setWorkflowModel(model, "AR");
        
        return "basic.jsp?content=arInvoiceMemo/arInvoiceMemoList";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-10-27 14:36:38
     * @author 
     * @param arInvoiceMemoHead
     * @param model
     * @return String
     *
     */
    @RequestMapping("getArInvoiceMemoHead")
    public String getArInvoiceMemoHead(ArInvoiceMemoHeadBase arInvoiceMemoHead, Model model) {
        //查询要编辑的数据
        if(arInvoiceMemoHead!=null&&StringUtils.isNotBlank(arInvoiceMemoHead.getInvoiceHeadCode())) {
            
            //根据version请求参数，判断数据从原表获取还是变更表获取
            if(arInvoiceMemoHead.getVersion()!=null&&arInvoiceMemoHead.getVersion()>0) {
                ArInvoiceMemoHeadBase arInvoiceMemoHeadTemp = this.arInvoiceMemoHeadMService.getDataObject(arInvoiceMemoHead.getInvoiceHeadCode(), arInvoiceMemoHead.getVersion());
                if(arInvoiceMemoHeadTemp!=null) {
                    arInvoiceMemoHead = arInvoiceMemoHeadTemp;
                }
            }else {
                ArInvoiceMemoHeadBase arInvoiceMemoHeadTemp = this.arInvoiceMemoHeadService.getDataObject(arInvoiceMemoHead.getInvoiceHeadCode());
                if(arInvoiceMemoHeadTemp!=null) {
                    arInvoiceMemoHead = arInvoiceMemoHeadTemp;
                }
            }
            
            //设置显示字段
            arInvoiceMemoHead.setStaffName(this.hrCommonService.getHrStaff(arInvoiceMemoHead.getStaffCode()).getStaffName());
            arInvoiceMemoHead.setDepartmentName(this.hrCommonService.getHrDepartment(arInvoiceMemoHead.getDepartmentCode()).getDepartmentName());
            
            //获取采购订单信息
            if(arInvoiceMemoHead.getInvoiceSourceType().equals("PO_INVOICE")) {
                //获取原发票信息
                ArInvoiceHead arInvoiceHead = this.arInvoiceHeadService.getDataObject(arInvoiceMemoHead.getInvoiceSourceHeadCode());
                //获取采购订单金额
                arInvoiceMemoHead.setSourceHeadAmount(arInvoiceHead.getAmount());
            }
            //获取收款人信息
            arInvoiceMemoHead.setPayerName(this.masterDataCommonService.getCustomerMap().get(arInvoiceMemoHead.getPayer()));
            //获取银行信息
            arInvoiceMemoHead.setBankName(this.datasetCommonService.getBank().get(arInvoiceMemoHead.getBankCode()));
            //获取客户相关信息
            try {
                MdCustomer mdCustomer = this.masterDataCommonService.getMdCustomerInfoCache(arInvoiceMemoHead.getPayer());
                arInvoiceMemoHead.setCustomerAddress(mdCustomer.getCustomerAddress());
                arInvoiceMemoHead.setCustomerContact(mdCustomer.getMdCustomerContactList().get(0).getContactName()+" "+mdCustomer.getMdCustomerContactList().get(0).getContactTelephone());
                arInvoiceMemoHead.setCustomerLicenseNumber(mdCustomer.getMdCustomerLicense().getLicenseNumber());
            }catch(Exception e) {}
        }else {
            //新增通知单
            //从发票生成通知单的情况
            if(StringUtils.isNotBlank(arInvoiceMemoHead.getInvoiceSourceHeadCode())&&StringUtils.isNotBlank(arInvoiceMemoHead.getInvoiceType())) {
                //获取原发票信息
                ArInvoiceHead arInvoiceHead = this.arInvoiceHeadService.getDataObject(arInvoiceMemoHead.getInvoiceSourceHeadCode());
                //将发票信息复制到通知单
                arInvoiceMemoHead.setReceiptMode(arInvoiceHead.getReceiptMode());
                arInvoiceMemoHead.setBankAccount(arInvoiceHead.getBankAccount());
                arInvoiceMemoHead.setBankCode(arInvoiceHead.getBankCode());
                arInvoiceMemoHead.setBankName(this.datasetCommonService.getBank().get(arInvoiceMemoHead.getBankCode()));
                arInvoiceMemoHead.setSubBankCode(arInvoiceHead.getSubBankCode());
                arInvoiceMemoHead.setCurrencyCode(arInvoiceHead.getCurrencyCode());
                arInvoiceMemoHead.setInvoiceSourceType("SO_INVOICE");
                arInvoiceMemoHead.setPayer(arInvoiceHead.getPayer());
                arInvoiceMemoHead.setSourceHeadAmount(arInvoiceHead.getAmount());
                arInvoiceMemoHead.setReceiver(arInvoiceHead.getReceiver());
                arInvoiceMemoHead.setPayerName(this.masterDataCommonService.getCustomerMap().get(arInvoiceMemoHead.getPayer()));
                //获取客户相关信息
                try {
                    MdCustomer mdCustomer = this.masterDataCommonService.getMdCustomerInfoCache(arInvoiceMemoHead.getPayer());
                    arInvoiceMemoHead.setCustomerAddress(mdCustomer.getCustomerAddress());
                    arInvoiceMemoHead.setCustomerContact(mdCustomer.getMdCustomerContactList().get(0).getContactName()+" "+mdCustomer.getMdCustomerContactList().get(0).getContactTelephone());
                    arInvoiceMemoHead.setCustomerLicenseNumber(mdCustomer.getMdCustomerLicense().getLicenseNumber());
                }catch(Exception e) {}
            }
            
            //初始化默认字段
            //receiptHead.setAmount(0D);
            arInvoiceMemoHead.setReceivedStatus("N");
            arInvoiceMemoHead.setStatus("NEW");
            
            //获取当前用户职员信息
            HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
            arInvoiceMemoHead.setStaffCode(staffInfo.getStaffCode());
            arInvoiceMemoHead.setDepartmentCode(staffInfo.getDepartmentCode());
            arInvoiceMemoHead.setStaffName(staffInfo.getStaffName());
            arInvoiceMemoHead.setDepartmentName(staffInfo.getDepartmentName());
        }
        
        //币种
        Map currencyTypeMap = this.datasetCommonService.getCurrencyType();
        //付款来源类型
        Map receiptSourceTypeMap = DataBox.getArInvoiceMemoSourceType();
        //状态
        Map receiptStatusMap = RDDataBox.getStatusMap();
        //获取出纳状态
        Map receivedStatusMap = DataBox.getReceivedStatusMap();
        //获取付款方式
        Map receiptModeMap = this.datasetCommonService.getPayMode();
        //获取供应商
        Map customerMap = this.masterDataCommonService.getCustomerMap();
        //获取本公司
        Map customerOwnMap = this.masterDataCommonService.getOwnVendorMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //发票类型
        Map invoiceTypeMap = DataBox.getArInvoiceMemoType();
        
        //页面属性设置
        model.addAttribute("receiptHead", arInvoiceMemoHead);
        model.addAttribute("currencyTypeMap", currencyTypeMap);
        model.addAttribute("receiptSourceTypeMap", receiptSourceTypeMap);
        model.addAttribute("receiptStatusMap", receiptStatusMap);
        model.addAttribute("receivedStatusMap", receivedStatusMap);
        model.addAttribute("receiptModeMap", receiptModeMap);
        model.addAttribute("customerMap", customerMap);
        model.addAttribute("customerOwnMap", customerOwnMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("invoiceTypeMap", invoiceTypeMap);
        //工作流属性
        this.setWorkflowModel(model, "AR", arInvoiceMemoHead.getInvoiceHeadCode());
        
        return "basic.jsp?content=arInvoiceMemo/arInvoiceMemoEdit";
    }
    
    
    
    /**
     * 
     * @description 获取销售订单选择框
     * @date 2020年7月20日
     * @author dongbin
     * @return
     * @return String
     *
     */
    @RequestMapping("getSelectSOModal")
    public String getSelectSOModal(Pages pages, SoHeadCO soHeadCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        
        //分页查询数据
        soHeadCO.setStatus("CONFIRM");
        soHeadCO.setApproveStatus("APPROVE");
        List<SoHead> soHeadList = this.soHeadService.getDataObjects(pages, soHeadCO);
        
        //采购订单类型
        Map soTypeMap = this.datasetCommonService.getSOType();
        //状态
        Map soStatusMap = com.erp.order.so.dao.data.DataBox.getSoStatusMap();
        //获取供应商
        Map customerMap = this.masterDataCommonService.getCustomerMap();
        //获取项目
        Map projectMap = this.masterDataCommonService.getProjectMap();
        
        //循环设置职员和组织信息
        for(SoHead soHead: soHeadList) {
            soHead.setStaffName(this.hrCommonService.getHrStaff(soHead.getStaffCode()).getStaffName());
            soHead.setDepartmentName(this.hrCommonService.getHrDepartment(soHead.getDepartmentCode()).getDepartmentName());
        }
        
        //页面属性设置
        model.addAttribute("soHeadList", soHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("soTypeMap", soTypeMap);
        model.addAttribute("soStatusMap", soStatusMap);
        model.addAttribute("customerMap", customerMap);
        model.addAttribute("projectMap", projectMap);
        
        return "arInvoice/pop/selectSOModal";
    }
    
    
    
    /**
     * 
     * @description 获取付款方对应的银行选择框
     * @date 2020年7月20日
     * @author dongbin
     * @return
     * @return String
     *
     */
    @RequestMapping("getSelectBankModal")
    public String getSelectBankModal(Pages pages, MdVendorBankCO mdVendorBankCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        pages.setMax(100);
        
        //分页查询数据
        List<MdVendorBank> mdVendorBankList = this.mdVendorBankService.getBankListByVendorCode(pages, mdVendorBankCO);
        
        //获取银行
        Map bankMap = this.datasetCommonService.getBank();
        
        
        //页面属性设置
        model.addAttribute("mdCustomerBankList", mdVendorBankList);
        model.addAttribute("pages", pages);
        model.addAttribute("bankMap", bankMap);
        
        return "arInvoice/pop/selectBankModal";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-10-27 14:36:38
     * @author 
     * @param arInvoiceMemoHead
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editArInvoiceMemoHead")
    public String editArInvoiceMemoHead(@Valid ArInvoiceMemoHead arInvoiceMemoHead, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        //参数校验
        Map<String, String> errorMap = this.validateParameters(bindingResult, model);
        if(errorMap.size()>0) {
            return "forward:getArInvoiceMemoHead";
        }
        
        try {
            //对当前编辑的对象初始化默认的字段
            
            //保存编辑的数据
            this.arInvoiceMemoHeadService.insertOrUpdateDataObject(arInvoiceMemoHead);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("invoiceHeadCode", arInvoiceMemoHead.getInvoiceHeadCode());
        }catch(Exception e){
            if(e.getCause().getClass()==ConstraintViolationException.class) {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "通知单编码已存在，请重新输入");
                return "redirect:/web/arInvoiceHead/getArInvoiceHeadList";
            }else {
                throw e;
            }
        }
        
        return "redirect:getArInvoiceMemoHead";
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-10-27 14:36:38
     * @author 
     * @param arInvoiceMemoHead
     * @return String
     *
     */
    @RequestMapping("deleteArInvoiceMemoHead")
    public String deleteArInvoiceMemoHead(ArInvoiceMemoHead arInvoiceMemoHead, RedirectAttributes attr) {
        //删除数据前验证数据
        if(arInvoiceMemoHead!=null&&arInvoiceMemoHead.getInvoiceHeadId()!=null) {
            if(arInvoiceMemoHead.getStatus().equals("NEW")) {
                //删除数据
                this.arInvoiceMemoHeadService.deleteDataObject(arInvoiceMemoHead);
                
                //提示信息
                attr.addFlashAttribute("hint", "success");
            }else {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "非新建状态的通知单不能删除");
            }
        }
        
        return "redirect:getArInvoiceMemoHeadList";
    }
    
    
    
    /**
     * 
     * @description 更新审批状态
     * @date 2020年8月4日
     * @author dongbin
     * @param code
     * @param approveStatus
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("updateApproveStatus")
    public String updateApproveStatus(String code, String invoiceSourceHeadCode, String approveStatus, RedirectAttributes attr) {
        
        if(StringUtils.isNotBlank(code)&&StringUtils.isNotBlank(approveStatus)) {
            if(approveStatus.equals("UNSUBMIT")) {
                boolean receiptFlag = this.arReceiptHeadService.isExistArReceiptRelateArInvoice(invoiceSourceHeadCode);
                if(receiptFlag) {
                    //提示信息
                    attr.addFlashAttribute("hint", "hint");
                    attr.addFlashAttribute("alertMessage", "当前关联的发票已收款核销不能变更");
                    attr.addAttribute("invoiceHeadCode", code);
                    return "redirect:getArInvoiceMemoHead";
                }
                
                //ECO===记录变更历史数据
                int errorCode = this.invoiceMemoEcoService.saveModifyHistory(code);
                if(errorCode!=0) {
                    //提示信息
                    attr.addFlashAttribute("hint", "hint");
                    attr.addFlashAttribute("alertMessage", "当前销售发票保存变更历史错误，无法变更");
                    attr.addAttribute("invoiceHeadCode", code);
                    return "redirect:getArInvoiceHead";
                }
            }
            
            //更新审核状态
            this.arInvoiceMemoHeadService.updateApproveStatus(code, approveStatus);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("invoiceHeadCode", code);
        }else {
            //提示信息
            attr.addFlashAttribute("hint", "hint");
            attr.addFlashAttribute("alertMessage", "提交或审批数据错误");
            attr.addAttribute("invoiceHeadCode", code);
        }
        
        return "redirect:getArInvoiceMemoHead";
    }
    
    
    
    /**
     * 
     * @description 更新数据状态
     * @date 2020年10月24日
     * @author dongbin
     * @param code
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("updateDataStatus")
    public String updateDataStatus(String code, String invoiceSourceHeadCode, String status, RedirectAttributes attr) {
        
        if(StringUtils.isNotBlank(code)&&StringUtils.isNotBlank(status)) {
            if(status.equals("CANCEL")) {
                boolean receiptFlag = this.arReceiptHeadService.isExistArReceiptRelateArInvoice(invoiceSourceHeadCode);
                if(receiptFlag) {
                    //提示信息
                    attr.addFlashAttribute("hint", "hint");
                    attr.addFlashAttribute("alertMessage", "当前关联的发票已收款核销不能取消");
                    attr.addAttribute("invoiceHeadCode", code);
                    return "redirect:getArInvoiceMemoHead";
                }
            }
            
            //更新审核状态
            this.arInvoiceMemoHeadService.updateDataStatus(code, status);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("invoiceHeadCode", code);
        }else {
            //提示信息
            attr.addFlashAttribute("hint", "hint");
            attr.addFlashAttribute("alertMessage", "修改数据状态错误");
            attr.addAttribute("invoiceHeadCode", code);
        }
        
        return "redirect:getArInvoiceMemoHead";
    }
    
    
    
    /**
     * 
     * @description 自动创建凭证分录
     * @date 2020年9月25日
     * @author dongbin
     * @param headCode
     * @return
     * @return String
     *
     */
    @RequestMapping("autoCreateVoucherEntry")
    @ResponseBody
    public String autoCreateVoucherEntry(String headCode, String invoiceType){
        try {
            //转换入库类型为单据类型
            String billType = com.erp.common.voucher.dao.data.DataBox.getVoucherTypeByBusinessType(invoiceType);
            
            //删除自动生成的凭证和分录
            //根据单据头code获取凭证头code
            String voucherHeadCode = this.finVoucherBillRService.getVoucherHeadCodeByBillHeadCode(billType, headCode);
            //删除凭证
            if(StringUtils.isNotBlank(voucherHeadCode)) {
                this.finVoucherHeadService.deleteFinVoucherHeadByVoucherHeadCode(voucherHeadCode);
            }
            
            //计算分录的金额
            //获取行
            List<ArInvoiceMemoLine> lineList = this.arInvoiceMemoLineService.getArInvoiceMemoLineListByHeadCode(headCode);
            
            BigDecimal voucherAmount = new BigDecimal(0D);
            BigDecimal amountSum = new BigDecimal(0D);
            BigDecimal taxAmountSum = new BigDecimal(0D);
            //循环获取加和
            for(ArInvoiceMemoLine line: lineList) {
                BigDecimal amount = line.getAmount();
                BigDecimal taxAmount = line.getTaxAmount();
                //计算合计金额
                amountSum = amountSum.add(amount);
                taxAmountSum = taxAmountSum.add(taxAmount);
                voucherAmount = voucherAmount.add(amount).add(taxAmount);
            }
            
            //调用自动创建方法
            this.finVoucherModelHeadService.autoCreateVoucher(headCode, new Double[]{Math.abs(voucherAmount.doubleValue()),Math.abs(amountSum.doubleValue()),Math.abs(taxAmountSum.doubleValue())}, billType);
            
            return JsonDataUtil.getExecuteJson(0);
        }catch(Exception e) {
            return JsonDataUtil.getExecuteJson(-1, "重新生成分录错误");
        }
    }
}
